package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.impl.EmployeeServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeServiceImpl employeeService;
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private PermissionMapper permissionMapper;

    /*权限管理*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录主体对象
        Subject subject = SecurityUtils.getSubject();
        //获取主体的身份对象（这里获取的对象与认证方法doGetAuthenticationInfo返回的SimpleAuthenticationInfo对象的第一个参数是同一个对象）
        Employee employee = (Employee) subject.getPrincipal();
        //判断是否是超级管理员
        if (employee.isAdmin()) {
            //info.addRole("admin"); //方便后续可以直接用subject来判断是否管理员
            info.addStringPermission("*:*"); //权限通配符
        } else {
            //根据用户的id查询该用户拥有的角色编码
            List<Role> roles = iRoleService.selectByEmpId(employee.getId());
            for (Role role : roles) {
                info.addRole(role.getSn());
            }
            //根据用户的id查询该用户拥有的权限表达式
            List<String> permissions = permissionMapper.selectByEmpId(employee.getId());
            info.addStringPermissions(permissions);
        }
        return info; //info对象中有哪些角色和权限，就代表当前登录用户拥有哪些角色和权限
    }

    /*身份验证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份验证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = (String) authenticationToken.getPrincipal();
        Employee employee = employeeService.selectByUsername(token.getUsername());
        if (employee == null) {
            //身份对象，真正的密码，当前realm的名字
            return null;
        }
        return new SimpleAuthenticationInfo("", employee.getPassword(), "");
    }
}
